package com.csnf.dao;

import com.csnf.entity.Authors;
import com.csnf.entity.Books;
import com.csnf.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    public List<Books> getBooksByName(String bookName) throws Exception {
        List<Books> booksList = new ArrayList<>();
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from books where book_name like concat('%',?,'%')";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn,sql,bookName);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Books book = JdbcUtil.invokeObject(rs,Books.class);
            String sql1 = "select * from authors where author_id=?";
            PreparedStatement ps1 = JdbcUtil.getPreparedStatement(conn,sql1,book.getAuthor_id());
            ResultSet rs1 = ps1.executeQuery();
            while (rs1.next()) {
                Authors authors = JdbcUtil.invokeObject(rs1,Authors.class);
                book.setAuthors(authors);
            }
            booksList.add(book);
            JdbcUtil.close(rs1,ps1);
        }
        JdbcUtil.close(rs,ps,conn);
        return booksList;
    }
}
